<template>
  <div class="dropdown" ref="dropdownRef">
    <a href="#" class="btn btn-outline-light my-2 dropdown-toggle" @click.prevent="toggleOpen">
      {{ title }}
    </a>
    <ul class="dropdown-menu" :style="{ display: 'block' }" v-if="isOpen">
      <DropDowmItem class="dropdown-item"><a href="#">发布专栏</a></DropDowmItem>
      <DropDowmItem class="dropdown-item"><a href="#">我的专栏</a></DropDowmItem>
      <DropDowmItem class="dropdown-item" :disabled="true"><a href="#">编辑资料</a></DropDowmItem>
      <DropDowmItem class="dropdown-item"><a href="#">退出登录</a></DropDowmItem>
    </ul>
  </div>
</template>

<script lang="ts">
import { defineComponent, ref, watch } from 'vue'
import DropDowmItem from './DropDownItem.vue'
import useClickOutside from '@/hooks/useClickOutside'

export default defineComponent({
  name: 'DropDown',
  components: {
    DropDowmItem
  },
  props: {
    title: {
      type: String,
      required: true,
      default: ''
    }
  },
  setup () {
    const isOpen = ref(false)
    const dropdownRef = ref<null | HTMLElement>(null)
    const toggleOpen = () => {
      isOpen.value = !isOpen.value
    }

    const isClickOutside = useClickOutside(dropdownRef)

    watch(isClickOutside, () => {
      if (isOpen.value && isClickOutside.value) {
        isOpen.value = false
      }
    })

    return {
      isOpen,
      toggleOpen,
      dropdownRef
    }
  }
})
</script>
